package com.jinken;

import javassist.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class TestTransformer implements ClassFileTransformer {

    private final String CLASS_NAME = "com.jinken.controller.HelloController";

    private final String METHOD_NAME = "hello";

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        //将所有的字节码的/替换成.
        className = className.replaceAll("/",".");
        if (CLASS_NAME.equals(className)){
            System.out.println("className = " + className);

            try {
                //获取字节码
                CtClass ctClass = ClassPool.getDefault().get(CLASS_NAME);
                //获取字节码的方法
                CtMethod helloMethod = ctClass.getDeclaredMethod("hello");




                //方法增强.方法执行执行，打印
                helloMethod.insertBefore("System.out.println(\"hello方法执行之前打印日志...\");");

                return ctClass.toBytecode();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        return null;
    }

}
